package com.daogu.fuelcard.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.util.WebUtils;

import java.util.Objects;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从cookie中取得token值
        String token = WebUtils.getCookie(request, "token") != null ? Objects.requireNonNull(WebUtils.getCookie(request, "token")).getValue() : null;
        if (token == null || Boolean.FALSE.equals(redisTemplate.hasKey(token))) {
            // token不存在或者在Redis中对应的key已经过期，重定向到登录页面
            response.sendRedirect("/login");
            // 返回false表示请求被拦截，不继续处理
            return false;
        }
        // token存在且有效，返回true表示继续处理请求
        return true;
    }
}